#!/bin/bash

list="3001 3002 3003 3004 3005 3006"
wsport=3000
auth=2999

function listapi() {
  echo "api pids:"
  for i in $list
  do
    pid=$(lsof -ti:$i)
    echo "  $i:$pid" 
  done
}

function listws() {
  pid=$(lsof -ti:$wsport)
  echo "ws 3000:$pid"
}

function killapi() {
  for i in $list
  do
    lsof -ti:$i | xargs kill >/dev/null 2>&1
  done
  echo "api stopped"
}

function killws() {
  lsof -ti:3000 | xargs kill >/dev/null 2>&1
  echo "ws stopped"
}

function listall() {
  listapi
  listws
}

function killall() {
  killapi
  killws
}

function startapi() {
  for i in $list
  do
    nohup python app.py $i >/dev/null 2>&1 &
  done
}

function startws() {
  nohup python ws.py $wsport >/dev/null 2>&1 &
}

function startall() {
  startws
  startapi
}

function checkapi() {
  for i in $list
  do
    echo "$i.log:"
    tail -n 3 logs/$i.log
  done
}

function checkws() {
  echo "ws.log:"
  tail -n 3 logs/$wsport.log
}

function checkall() {
  checkws
  checkapi
}

function join_by { local IFS="$1"; shift; echo "$*"; }

function monitor() {
  s=$(join_by , $wsport $list $auth)
  pids=( $(lsof -ti:$s) )
  top "${pids[@]/#/-p }"
}

cd /data/webserver

if [[ $1 == "stop" ]]; then
  listall
  killall
fi

if [[ $1 == "list" ]]; then
  listall
fi

if [[ $1 == "start" ]]; then
  startall
  listall
fi

if [[ $1 == "restart" ]]; then
  killall
  echo ""
  echo "wait to start all processes..."
  sleep 1
  startall
  echo "processes started, wait to get all pids..."
  echo ""
  sleep 1
  listall
fi

if [[ $1 == "check" ]]; then
  checkall
fi

if [[ $1 == "monitor" ]]; then
  monitor
fi

